//
//  AuthenticationViewController.m
//  MagictoHire
//
//  Created by 锋 on 2017/12/13.
//  Copyright © 2017年 HUAYU. All rights reserved.
//

#import "AuthenticationViewController.h"
#import "UploadAuthenticationPictureView.h"
#import "CompleteView.h"
#import <Photos/PHPhotoLibrary.h>
#import <MobileCoreServices/MobileCoreServices.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/ALAsset.h>
#import <AssetsLibrary/ALAssetsGroup.h>
#import <AssetsLibrary/ALAssetsLibrary.h>
#import <AssetsLibrary/ALAssetRepresentation.h>
#import "AuthenticationMessageModel.h"
#import "SecurityDepositViewController.h"

@interface AuthenticationViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate, UINavigationControllerDelegate, UIImagePickerControllerDelegate>
{
    NSString *agreementStr;
    UIButton *agreement;
    BOOL isSelect;
}
@property (weak, nonatomic) IBOutlet UIButton *fillDataBtn;
@property (weak, nonatomic) IBOutlet UIButton *uploadPictureBtn;
@property (weak, nonatomic) IBOutlet UIButton *completeBtn;
@property (weak, nonatomic) IBOutlet UILabel *underLineLabel;
@property (weak, nonatomic) IBOutlet UIButton *nextBtn;
@property (nonatomic, strong) NSArray *identityMessageArr;
@property (nonatomic, strong) UITableView *fillDataTableView;
@property (nonatomic, strong) UploadAuthenticationPictureView *uploadAuthenticationPictureView;
@property (nonatomic, strong) CompleteView *completeView;
@property (nonatomic, strong) NSArray *nameArr;
@property (nonatomic, strong) dispatch_source_t timer;
@property (nonatomic, assign) NSInteger imageSign;
@property (nonatomic, copy) NSString *firstImageString;
@property (nonatomic, copy) NSString *secondImageString;
@property (nonatomic, copy) NSString *thirdImageString;

@property (nonatomic, strong) UIView *coverView;
@property (nonatomic, strong) UIView *tipView;
@end

@implementation AuthenticationViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    isSelect = YES;
    _nameArr = @[@"营业执照编号", @"姓名", @"身份证号码", @"联系方式"];
    [self requestRegistAgreement];
    [self setupUI];
    [self setupFillDataTableView];
    [self requestIdentityMessage];
    // Do any additional setup after loading the view from its nib.
}

- (void)setupUI {
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"实名认证";
    self.view.backgroundColor = RGB(242, 242, 242);
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
    singleTap.cancelsTouchesInView = NO;
    [self.view addGestureRecognizer:singleTap];
    
    agreement = [ZCControl createButtonWithFrame:CGRectMake(30*displaywidth, 241, SCREEN_WIDTH-60*displaywidth, 20*displaywidth) ImageName:@"gouxuandaik" Target:self Action:@selector(agreementAction) Title:@"《身份认证协议》" Font:12.0];
    [agreement setTitleColor:RGB(255, 111, 25) forState:UIControlStateNormal];
    [self.view addSubview:agreement];
}

//协议
- (void)agreementAction
{
    [self showTipView];
}

- (void)showTipView {
    UIWindow *window = [UIApplication sharedApplication].keyWindow;
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tipViewKeyboardHide:)];
    singleTap.cancelsTouchesInView = NO;
    [window addGestureRecognizer:singleTap];
    if (!_coverView) {
        _coverView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _coverView.backgroundColor = [UIColor blackColor];
        _coverView.alpha = 0;
        [window addSubview:_coverView];
    }
    _coverView.hidden = NO;
    
    if (!_tipView) {
        _tipView = [[UIView alloc] initWithFrame:CGRectMake(40, (SCREEN_HEIGHT - 400*displaywidth)/2, SCREEN_WIDTH - 80, 400*displaywidth)];
        _tipView.backgroundColor = [UIColor whiteColor];
        _tipView.alpha = 0;
        _tipView.layer.cornerRadius = 2;
        _tipView.layer.masksToBounds = YES;
        [window addSubview:_tipView];
    }
    _tipView.hidden = NO;
    [UIView transitionWithView:_coverView duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
        _coverView.alpha = 0.4;
        _tipView.alpha = 1;
    } completion:nil];
    UILabel *tipLabel = [[UILabel alloc] initWithFrame:CGRectMake(0, 16, _tipView.frame.size.width, 30)];
    tipLabel.text = @"《身份认证协议》";
    tipLabel.textAlignment = NSTextAlignmentCenter;
    tipLabel.font = [UIFont systemFontOfSize:18];
    tipLabel.textColor = UIColorHexValue(0x4D4D4D);
    [_tipView addSubview:tipLabel];
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectMake(18, 56, _tipView.frame.size.width - 36, 250*displaywidth)];
    [webView loadHTMLString:agreementStr baseURL:nil];
    webView.backgroundColor = [UIColor whiteColor];
    [_tipView addSubview:webView];
    
    UILabel *lineLabel = [ZCControl createLabelWithFrame:CGRectMake(0, _tipView.frame.size.height - 50, _tipView.frame.size.width, 1) Font:16 Text:nil Color:nil];
    lineLabel.backgroundColor = RGB(233, 234, 233);
    [_tipView addSubview:lineLabel];
    
    UIButton *cancelBtn = [[UIButton alloc] initWithFrame:CGRectMake(25, _tipView.frame.size.height - 40, (_tipView.frame.size.width - 100) / 2, 30)];
    cancelBtn.titleLabel.font = [UIFont systemFontOfSize:16];
    [cancelBtn setTitleColor:ThemeColor forState:UIControlStateNormal];
    cancelBtn.layer.cornerRadius = 5;
    cancelBtn.layer.masksToBounds = YES;
    cancelBtn.layer.borderColor = ThemeColor.CGColor;
    cancelBtn.layer.borderWidth = 1;
    cancelBtn.backgroundColor = [UIColor whiteColor];
    [cancelBtn setTitle:@"不同意" forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(onClickCancelBtn) forControlEvents:UIControlEventTouchUpInside];
    [_tipView addSubview:cancelBtn];
    UIButton *ensureBtn = [[UIButton alloc] initWithFrame:CGRectMake(25*3 + (_tipView.frame.size.width - 100) / 2, _tipView.frame.size.height - 40, (_tipView.frame.size.width - 100) / 2, 30)];
    ensureBtn.titleLabel.font = [UIFont systemFontOfSize:15];
    ensureBtn.backgroundColor = ThemeColor;
    ensureBtn.layer.cornerRadius = 5;
    ensureBtn.layer.masksToBounds = YES;
    [ensureBtn setTitle:@"同意" forState:UIControlStateNormal];
    [ensureBtn addTarget:self action:@selector(onClickEnsureBtn) forControlEvents:UIControlEventTouchUpInside];
    [_tipView addSubview:ensureBtn];
}

- (void)onClickCancelBtn {
    isSelect = NO;
    [agreement setImage:[UIImage imageNamed:@"xuankuang3"] forState:UIControlStateNormal];
    [self hideTipView];
}

- (void)onClickEnsureBtn {
    isSelect = YES;
    [agreement setImage:[UIImage imageNamed:@"gouxuandaik"] forState:UIControlStateNormal];
    [self hideTipView];
}

-(void)tipViewKeyboardHide:(UITapGestureRecognizer*)tap {
    [self hideTipView];
}

- (void)hideTipView {
    if (_coverView) {
        [UIView transitionWithView:_coverView duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            _coverView.alpha = 0;
        } completion:nil];
        _coverView.hidden = YES;
    }
    if (_tipView) {
        [UIView transitionWithView:_tipView duration:0.2 options:UIViewAnimationOptionTransitionCrossDissolve animations:^{
            _tipView.alpha = 0;
        } completion:nil];
        _tipView.hidden = YES;
    }
}

- (void)requestRegistAgreement {
    WEAKSELF;
    //    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestGetRegistAgreeMentParmers:@{@"key":@"contractor_identity_agreement"} Success:^(id obj)
     {
         //         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             agreementStr = obj[@"data"][@"propertyValue"];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         //         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

- (void)setupFillDataTableView {
    _fillDataTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 45, SCREEN_WIDTH, _nameArr.count * 44) style:UITableViewStyleGrouped];
    _fillDataTableView.delegate = self;
    _fillDataTableView.dataSource = self;
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0.000001)];
    view.backgroundColor = [UIColor whiteColor];
    _fillDataTableView.tableHeaderView = view;
    _fillDataTableView.tableFooterView = view;
    _fillDataTableView.scrollEnabled = NO;
    _fillDataTableView.backgroundColor = [UIColor whiteColor];
    _fillDataTableView.separatorColor = RGB(242, 242, 242);
    [self.view addSubview:_fillDataTableView];
}

- (void)setupUploadAuthenticationPictureView {
    _uploadAuthenticationPictureView = [[NSBundle mainBundle] loadNibNamed:@"UploadAuthenticationPictureView" owner:self options:nil].lastObject;
    _uploadAuthenticationPictureView.preBtn.layer.borderColor = [ThemeColor CGColor];
    _uploadAuthenticationPictureView.preBtn.layer.borderWidth = 1;
    _uploadAuthenticationPictureView.frame = CGRectMake(0, 61, SCREEN_WIDTH, 478);

//    _uploadAuthenticationPictureView.IdCardFrontPicture.contentMode = UIViewContentModeScaleAspectFill;
//    _uploadAuthenticationPictureView.IdCardFrontPicture.clipsToBounds = YES;
//    [_uploadAuthenticationPictureView.IdCardFrontPicture setContentScaleFactor:[[UIScreen mainScreen] scale]];
//
//    _uploadAuthenticationPictureView.BusinessLicense.contentMode = UIViewContentModeScaleAspectFill;
//    _uploadAuthenticationPictureView.BusinessLicense.clipsToBounds = YES;
//    [_uploadAuthenticationPictureView.BusinessLicense setContentScaleFactor:[[UIScreen mainScreen] scale]];
//
//    _uploadAuthenticationPictureView.IdCardReversedPicture.contentMode = UIViewContentModeScaleAspectFill;
//    _uploadAuthenticationPictureView.IdCardReversedPicture.clipsToBounds = YES;
//    [_uploadAuthenticationPictureView.IdCardReversedPicture setContentScaleFactor:[[UIScreen mainScreen] scale]];
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseIdCardFrontPicture)];
    [_uploadAuthenticationPictureView.zmBackgImageView addGestureRecognizer:tap];
    UITapGestureRecognizer *tap1 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseIdCardReversedPicture)];
    [_uploadAuthenticationPictureView.fanmBackImageView addGestureRecognizer:tap1];
    UITapGestureRecognizer *tap2 = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(chooseBusinessLicense)];
    [_uploadAuthenticationPictureView.businBackImageView addGestureRecognizer:tap2];
    
    [_uploadAuthenticationPictureView.preBtn addTarget:self action:@selector(onClickFillDataBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_uploadAuthenticationPictureView.nextBtn addTarget:self action:@selector(onClickUploadPictureNextBtn) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_uploadAuthenticationPictureView];
}

- (void)setupCompleteView {
    _completeView = [[NSBundle mainBundle] loadNibNamed:@"CompleteView" owner:self options:nil].lastObject;
    _completeView.frame = CGRectMake(0, 95, SCREEN_WIDTH, 281);
    [self giveImageViewDynamic];
    [_completeView.completeBtn addTarget:self action:@selector(goBack) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:_completeView];
}

// MARK:tableview的方法
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 4;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 44;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.000001;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.000001;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSString *ID = @"cellID";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if (!cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:ID];
    }
    if (![self.view viewWithTag:indexPath.row + 100]) {
        UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(134, 0, SCREEN_WIDTH - 115, 44)];
        textField.backgroundColor = [UIColor clearColor];
        textField.delegate = self;
        textField.tag = indexPath.row + 100;
        textField.textAlignment = NSTextAlignmentLeft;
        textField.textColor = UIColorHexValue(0xB3B3B3);
        if (indexPath.row == 0) {
            textField.placeholder = @"请输入营业执照编号";
            textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        } else if (indexPath.row == 1) {
            textField.placeholder = @"请输入法人姓名";
        } else if (indexPath.row == 2) {
            textField.placeholder = @"请输入法人身份证号码";
            textField.keyboardType = UIKeyboardTypeNumbersAndPunctuation;
        } else if (indexPath.row == 3) {
            textField.keyboardType = UIKeyboardTypePhonePad;
            textField.placeholder = @"请输入法人联系方式";
        }
        [cell.contentView addSubview:textField];
    }
    UITextField *textField = [self.view viewWithTag:indexPath.row + 100];
    if (_identityMessageArr.count > 0) {
        AuthenticationMessageModel *model = _identityMessageArr[0];
        if (model) {
            if (indexPath.row == 0) {
                textField.text = model.businessLicenseNum;
            } else if (indexPath.row == 1) {
                textField.text = model.realName;
            } else if (indexPath.row == 2) {
                textField.text = model.idCardNum;
            } else if (indexPath.row == 3) {
                textField.text = model.contactInfo;
            }
        }
    }
    cell.textLabel.textColor = UIColorHexValue(0x4D4D4D);
    cell.textLabel.text = _nameArr[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

//MARK:点击方法
- (void)goBack {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)keyboardHide:(UITapGestureRecognizer*)tap {
    [self.view endEditing:YES];
}

- (void)onClickUploadPictureNextBtn {
    if ([_uploadAuthenticationPictureView.IdCardFrontPicture.image isEqual:[UIImage imageNamed:@"zm"]] || [_firstImageString isEqualToString:@""] || [_firstImageString isKindOfClass:[NSNull class]]) {
        [LTools showMBProgressWithText:@"请输入选择身份证正面照片" addToView:self.view];
        return;
    }
    if ([_uploadAuthenticationPictureView.IdCardReversedPicture.image isEqual:[UIImage imageNamed:@"fanm"]] || [_secondImageString isEqualToString:@""] || [_secondImageString isKindOfClass:[NSNull class]]) {
        [LTools showMBProgressWithText:@"请输入选择身份证反面照片" addToView:self.view];
        return;
    }
    if ([_uploadAuthenticationPictureView.BusinessLicense.image isEqual:[UIImage imageNamed:@"zhiz"]] || [_thirdImageString isEqualToString:@""] || [_thirdImageString isKindOfClass:[NSNull class]]) {
        [LTools showMBProgressWithText:@"请输入选择营业执照" addToView:self.view];
        return;
    }
    
    [self requestIdentitySave];
}

- (void)onClickUploadPicturePreBtn {
    [self onClickFillDataBtn:_fillDataBtn];
}

- (IBAction)onClickNextBtn:(UIButton *)sender {
    if (!isSelect) {
        [LTools showMBProgressWithText:@"请先勾选协议,才可认证" addToView:self.view];
        return;
    }
    UITextField *textField = [self.view viewWithTag:100];
    UITextField *textField1 = [self.view viewWithTag:101];
    UITextField *textField2 = [self.view viewWithTag:102];
    UITextField *textField3 = [self.view viewWithTag:103];

    if (textField.text.length<15||textField.text.length>18) {
        [LTools showMBProgressWithText:@"营业执照编号输入错误,请重新输入" addToView:self.view];
        return;
    }
    if ([textField1.text isEqualToString:@""]) {
        [LTools showMBProgressWithText:@"请输入法人姓名" addToView:self.view];
        return;
    }
    if (textField2.text.length!=18) {
        [LTools showMBProgressWithText:@"身份证号码输入错误,请重新输入" addToView:self.view];
        return;
    }
    if (textField3.text.length!=11) {
        [LTools showMBProgressWithText:@"手机号码输入错误,请重新输入" addToView:self.view];
        return;
    }
    [self onClickUploadPictureBtn:_uploadPictureBtn];
}

- (IBAction)onClickFillDataBtn:(UIButton *)sender {
    _fillDataBtn.selected = YES;
    _uploadPictureBtn.selected = NO;
    _completeBtn.selected = NO;
    _fillDataBtn.enabled = YES;
    _uploadPictureBtn.enabled = NO;
    _completeBtn.enabled = NO;
    if (_fillDataBtn.selected) {
        if (!_fillDataTableView) {
            [self setupFillDataTableView];
        }
        _uploadAuthenticationPictureView.hidden = YES;
        _completeView.hidden = YES;
        _nextBtn.hidden = NO;
        agreement.hidden = NO;
        _fillDataTableView.hidden = NO;
        [Utilities underLineSlideAnimation:_underLineLabel withAlignView:_fillDataBtn andAnimationView:nil];
    }
}
- (IBAction)onClickUploadPictureBtn:(UIButton *)sender {
    _uploadPictureBtn.selected = YES;
    _fillDataBtn.selected = NO;
    _completeBtn.selected = NO;
    _uploadPictureBtn.enabled = YES;
    _completeBtn.enabled = NO;
    _fillDataBtn.enabled = NO;
    if (_uploadPictureBtn.selected) {
        if (!_uploadAuthenticationPictureView) {
            [self setupUploadAuthenticationPictureView];
        }
        _uploadAuthenticationPictureView.hidden = NO;
        _completeView.hidden = YES;
        _nextBtn.hidden = YES;
        agreement.hidden = YES;
        _fillDataTableView.hidden = YES;
        [Utilities underLineSlideAnimation:_underLineLabel withAlignView:_uploadPictureBtn andAnimationView:nil];
        if (_identityMessageArr.count > 0) {
            AuthenticationMessageModel *model = _identityMessageArr[0];
            if (model) {
                [_uploadAuthenticationPictureView.IdCardFrontPicture sd_setImageWithURL:[NSURL URLWithString:model.idCardFrontImg] placeholderImage:nil];
                [_uploadAuthenticationPictureView.IdCardReversedPicture sd_setImageWithURL:[NSURL URLWithString:model.idCardBackImg] placeholderImage:nil];
                [_uploadAuthenticationPictureView.BusinessLicense sd_setImageWithURL:[NSURL URLWithString:model.businessLicenseImg] placeholderImage:nil];
                _uploadAuthenticationPictureView.IdCardFrontPictureLabel.hidden = YES;
                _uploadAuthenticationPictureView.IdCardReversedPictureLabel.hidden = YES;
                _uploadAuthenticationPictureView.BusinessLicenseLabel.hidden = YES;
            }
        }
    }
}
- (IBAction)onClickCompleteBtn:(UIButton *)sender {
    _completeBtn.selected = YES;
    _uploadPictureBtn.selected = NO;
    _fillDataBtn.selected = NO;
    _completeBtn.enabled = YES;
    _uploadPictureBtn.enabled = NO;
    _fillDataBtn.enabled = NO;
    if (_completeBtn.selected) {
        if (!_completeView) {
            [self setupCompleteView];
        }
        _uploadAuthenticationPictureView.hidden = YES;
        _completeView.hidden = NO;
        _nextBtn.hidden = YES;
        agreement.hidden = YES;
        _fillDataTableView.hidden = YES;
        [Utilities underLineSlideAnimation:_underLineLabel withAlignView:_completeBtn andAnimationView:nil];
    }
}

//MARK:请求数据
- (void)requestIdentitySave {
    WEAKSELF;
    UITextField *textField = [self.view viewWithTag:100];
    UITextField *textField1 = [self.view viewWithTag:101];
    UITextField *textField2 = [self.view viewWithTag:102];
    UITextField *textField3 = [self.view viewWithTag:103];
    if (_identityMessageArr.count > 0) {
        AuthenticationMessageModel *model = _identityMessageArr[0];
        if (model) {
            _firstImageString = model.idCardFrontImg;
            _secondImageString = model.idCardBackImg;
            _thirdImageString = model.businessLicenseImg;
        }
    }
    NSDictionary *dic = @{@"businessLicenseImg" : _thirdImageString, @"businessLicenseNum" : textField.text, @"contactInfo" : textField3.text, @"idCardBackImg" : _secondImageString, @"idCardFrontImg" : _firstImageString, @"idCardNum" : textField2.text, @"realName" : textField1.text};
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestIdentitySaveParmers:dic Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             NSString *orderCode = obj[@"data"][@"order"][@"code"];
             NSString *price = obj[@"data"][@"order"][@"price"];
             SecurityDepositViewController *vc = [[SecurityDepositViewController alloc] init];
             vc.priceStr = price;
             vc.orderNo = orderCode;
             [weakSelf.navigationController pushViewController:vc animated:YES];
//             [self onClickCompleteBtn:_completeBtn];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

- (void)requestIdentityMessage {
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HYBaseHandler requestIdentityMineParmers:nil Success:^(id obj)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([obj server_Getcodecheck])
         {
             NSLog(@"%@", obj);
             _identityMessageArr = [AuthenticationMessageModel mj_objectArrayWithKeyValuesArray:@[obj[@"data"]]];
             [_fillDataTableView reloadData];
         }
         else
         {
             [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
         }
     } failed:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         
     }];
}

//给imageView加动态
- (void)giveImageViewDynamic {
    __block NSString *str =@"di1";
    [_completeView.statusImageView setImage:[UIImage imageNamed:str]];
    //定时器开始执行的延时时间
    NSTimeInterval delayTime = 0.0f;
    //定时器间隔时间
    NSTimeInterval timeInterval = 0.5f;
    //创建子线程队列
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    //使用之前创建的队列来创建计时器
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    //设置延时执行时间，delayTime为要延时的秒数
    dispatch_time_t startDelayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayTime * NSEC_PER_SEC));
    //设置计时器
    dispatch_source_set_timer(_timer, startDelayTime, timeInterval * NSEC_PER_SEC, 0.1 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(_timer, ^{
        //执行事件
        if ([str isEqualToString:@"di1"]) {
            str = @"di2";
        } else if ([str isEqualToString:@"di2"]) {
            str = @"di3";
        } else if ([str isEqualToString:@"di3"]) {
            str = @"di4";
        } else if ([str isEqualToString:@"di4"]) {
            str = @"di5";
        } else if ([str isEqualToString:@"di5"]) {
            str = @"di1";
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [_completeView.statusImageView setImage:[UIImage imageNamed:str]];
        }) ;
    });
    // 启动计时器
    dispatch_resume(_timer);
}

- (void)chooseIdCardFrontPicture {
    _imageSign = 1;
    [self choosePicture];
}

- (void)chooseIdCardReversedPicture {
    _imageSign = 2;
    [self choosePicture];
}

- (void)chooseBusinessLicense {
    _imageSign = 3;
    [self choosePicture];
}

- (void)choosePicture {
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"选择图片" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //拍照
    [alertVC addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"拍照");
        [self takePhoto];
        
    }]];
    
    //从相册中选取
    [alertVC addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        HYLog(@"从相册中选取");
        [self choseImageWithTypeCameraTypePhotoLibrary:UIImagePickerControllerSourceTypePhotoLibrary];
        
    }]];
    [alertVC addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        HYLog(@"取消");
        [self dismissViewControllerAnimated:NO completion:nil];
    }]];
    
    [self presentViewController:alertVC animated:YES completion:nil];
}

// MARK:系统自带相册
-(void)takePhoto
{
    //判断是否打开相机权限
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if (authStatus == AVAuthorizationStatusRestricted || authStatus ==AVAuthorizationStatusDenied)
    {
        UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您尚未开启相机权限，请去系统设置界面打开相机权限！" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
        }];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    else
    {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
        if ([UIImagePickerController isSourceTypeAvailable: UIImagePickerControllerSourceTypeCamera])
        {
            UIImagePickerController *picker = [[UIImagePickerController alloc] init];
            picker.delegate = self;
            //设置拍照后的图片可被编辑
            picker.allowsEditing = YES;
            picker.sourceType = sourceType;
            
            [self presentViewController:picker animated:YES completion:nil];
        }else
        {
            
        }
        
    }
}

-(void)choseImageWithTypeCameraTypePhotoLibrary:(UIImagePickerControllerSourceType)type{
    
    UIImagePickerController * imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.delegate = self;
    imagePicker.sourceType = type;
    imagePicker.allowsEditing = YES;
    imagePicker.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
    [self presentViewController:imagePicker animated:YES completion:^{
        
    }];
}
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    //    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSString *type = [info objectForKey:UIImagePickerControllerMediaType];
    if ([type isEqualToString:@"public.image"]) {
        UIImageOrientation imageOrientation = image.imageOrientation;
        if(imageOrientation!=UIImageOrientationUp)
        {
            UIGraphicsBeginImageContext(image.size);
            [image drawInRect:CGRectMake(0, 0, image.size.width, image.size.height)];
            image = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
        }
        
    }
    
    if (_imageSign == 1) {
        _uploadAuthenticationPictureView.IdCardFrontPicture.image = image;
        _uploadAuthenticationPictureView.IdCardFrontPictureLabel.hidden = YES;
    } else if (_imageSign == 2) {
        _uploadAuthenticationPictureView.IdCardReversedPicture.image = image;
        _uploadAuthenticationPictureView.IdCardReversedPictureLabel.hidden = YES;
    } else if (_imageSign == 3) {
        _uploadAuthenticationPictureView.BusinessLicense.image = image;
        _uploadAuthenticationPictureView.BusinessLicenseLabel.hidden = YES;
    }
    
    WEAKSELF;
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HttpTool uploadImageWithPath:SERVER_PictureUpload params:nil thumbName:@"file" image:image success:^(id json)
     {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         if ([json server_Getcodecheck])
         {
             NSArray *dataArr = json[@"data"];
             if (_imageSign == 1) {
                 _firstImageString = dataArr[0];
             } else if (_imageSign == 2) {
                 _secondImageString = dataArr[0];
             } else if (_imageSign == 3) {
                 _thirdImageString = dataArr[0];
             }
         }
         
     } failure:^(NSError *error) {
         [MBProgressHUD hideAllHUDsForView:weakSelf.view animated:YES];
         [LTools showMBProgressWithText:@"上传失败,请重试" addToView:self.view];
     } progress:^(CGFloat progress) {
         
     }];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
